package com.example.fairplay.newfpregistration.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fairplay.newfpregistration.R;
import com.example.mylibrary.CallBack;
import com.example.mylibrary.MyApp;
import com.example.mylibrary.data.Sort;
import com.example.mylibrary.data.StudentInfo;
import com.example.mylibrary.tcp.PackageHeadInfo;
import com.example.mylibrary.tcp.ResultPackage;
import com.example.mylibrary.tcp.SocketClient;
import com.example.mylibrary.tcp.TCPConst;
import com.example.mylibrary.util.ExlUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.aratek.facelib.AraFaceAuthLib;

import static com.example.mylibrary.tcp.TCPConst.MAX_RECORD_COUNT;


public class SetingSystemActivity extends AppCompatActivity   {

    @Bind(R.id.rg_face)
    RadioGroup faceGroup;
    @Bind(R.id.rb_open_face)
    RadioButton faceOpenRB;
    @Bind(R.id.rb_close_face)
    RadioButton facecloseRB;
    @Bind(R.id.rg_FP)
    RadioGroup fpGroup;
    @Bind(R.id.rb_open_FP)
    RadioButton fpOpenRB;
    @Bind(R.id.rb_close_FP)
    RadioButton fpcloseRB;
    @Bind(R.id.rg_Group)
    RadioGroup gpGroup;
    @Bind(R.id.rb_open_Group)
    RadioButton groupopenRB;
    @Bind(R.id.rb_close_Group)
    RadioButton groupcloseRB;
    @Bind(R.id.editIP)
    EditText editIP;
    @Bind(R.id.editlocal)
    EditText editlocal;
    @Bind(R.id.tv_state_yn)
    TextView stateText;
    @Bind(R.id.editface)
    EditText editface;


    private List<String> spinnerSortArr = new ArrayList<>();
    private List<String>  spinnerItemArr = new ArrayList<>();
    private List<String> spinnerGroupArr = new ArrayList<>();
    public static final int EXEL_READ_SUCCESS = 0X0;
    public static final int EXEL_READ_FAIL    = 0X1;
    private List<StudentInfo> studentInfos;
    private StudentInfo studentInfo;
    private static final String path = "/sdcard/FP-KTA2203/infos.xls";
//    private static final String path1 = "/sdcard/ItemGrop.xls";
//    private static final String path2 = "/sdcard/Item.xls";
    private String ip;
    private String local;
    private ResultPackage rcPackage;
    private AraFaceAuthLib araFaceAuthLib;
    private ProgressDialog mProgressDialog;
    private boolean b1;
    private Handler mHandler;
    private ArrayAdapter<String> spinnerSortAdapter;
    private ArrayAdapter<String> spinnerItemAdapter;
    private ArrayAdapter<String> spinnerGroupAdapter;
    private List<Sort> sorts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seting_system);
        ButterKnife.bind(this);
        if (fpOpenRB.isChecked() == true) {
            facecloseRB.setChecked(true);
        } else if(fpOpenRB.isChecked() == false){
            facecloseRB.setChecked(false);
        }
        initView();
        araFaceAuthLib = MainMenu.getAraFaceAuthLib();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        setListenerForView();
        ExlUtils.getInstance().setExlListener(new ExlUtils.ExlListener() {
            @Override
            public void onExlResponse(final int responseCode) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e( "mProgressDialog: ", responseCode+" 0");
                        switch (responseCode){
                            case EXEL_READ_SUCCESS:
                                    mProgressDialog.dismiss();
                                Log.e( "mProgressDialog: ", responseCode+" 1");
                                break;
                            case EXEL_READ_FAIL:

                                break;
                        }
                    }
                });
            }
        });
    }


    //保存选项状态    在TransitionActivity里进行改变
    private  void setListenerForView(){
        faceGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (R.id.rb_open_face == checkedId) {
                    Log.i("人脸认证", "打开");
                    MyApp.mACache.put("人脸认证", "true");
                } else if (R.id.rb_close_face == checkedId) {
                    Log.i("人脸认证", "关闭");
                    MyApp.mACache.put("人脸认证", "false");
                }
            }

        });
        if (MyApp.mACache.getAsString("人脸认证") != null) {
            //开启人脸
            if (Boolean.valueOf(MyApp.mACache.getAsString("人脸认证"))) {
                faceOpenRB.setChecked(true);
                //关闭人脸
            } else {
                facecloseRB.setChecked(true);
            }
        }
        //指纹模块
        fpGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (R.id.rb_open_FP == checkedId) {
                    Log.i("指纹认证", "打开");
                    MyApp.mACache1.put("指纹认证", "true");
                } else if (R.id.rb_close_FP == checkedId) {
                    Log.i("指纹认证", "关闭");
                    MyApp.mACache1.put("指纹认证", "false");
                }
            }
        });

        if (MyApp.mACache1.getAsString("指纹认证") != null) {
            //开启指纹
            if (Boolean.valueOf(MyApp.mACache1.getAsString("指纹认证"))) {
                fpOpenRB.setChecked(true);
                //关闭指纹
            } else {
                fpcloseRB.setChecked(true);
            }
        }

        //分组
        gpGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (R.id.rb_open_Group == checkedId) {
                    Log.i("是否开启分组", "打开");
                    MyApp.mAcache2.put("是否开启分组", "true");
                } else if (R.id.rb_close_Group == checkedId) {
                    Log.i("是否开启分组", "关闭");
                    MyApp.mAcache2.put("是否开启分组", "false");
                }
            }
        });
        if (MyApp.mAcache2.getAsString("是否开启分组") != null) {
            //开启指纹
            if (Boolean.valueOf(MyApp.mAcache2.getAsString("是否开启分组"))) {
                groupopenRB.setChecked(true);
                //关闭指纹
            } else {
                groupcloseRB.setChecked(true);
            }
        }

    }

    private void initView() {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setCancelable(false);
        SharedPreferences sp=getSharedPreferences("data",0);
        String ip = sp.getString("Ip", "");
        String local= sp.getString("local", "");
        float faceScore = sp.getFloat("faceScore",0);
        editface.setText(faceScore+"");
        editIP.setText(ip);
        editlocal.setText(local);

    }


    @OnClick({R.id.rb_open_Group,R.id.rb_close_Group,R.id.rb_open_FP,R.id.rb_close_FP,R.id.rb_open_face,R.id.rb_close_face,R.id.btn_save,R.id.readInfo,R.id.btn_import_grou,R.id.btn_download,R.id.btn_download_Test})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.rb_open_Group:
                Toast.makeText(this, "打开分道", Toast.LENGTH_SHORT).show();

                break;
            case R.id.rb_close_Group:
                Toast.makeText(this, "关闭分道", Toast.LENGTH_SHORT).show();

                break;
            case R.id.rb_open_FP:
                Toast.makeText(this, "打开指纹认证", Toast.LENGTH_SHORT).show();
                if (fpOpenRB.isChecked() == true ){
                    facecloseRB.setChecked(true);
                }
                break;
            case R.id.rb_close_FP:
                Toast.makeText(this, "关闭指纹认证", Toast.LENGTH_SHORT).show();
                    faceOpenRB.setChecked(true);

                break;
            case R.id.rb_open_face:
                Toast.makeText(this, "打开人脸认证", Toast.LENGTH_SHORT).show();
                if (faceOpenRB.isChecked() == true ){
                    fpcloseRB.setChecked(true);
                }
                break;
            case R.id.rb_close_face:
                Toast.makeText(this, "关闭人脸认证", Toast.LENGTH_SHORT).show();
                fpcloseRB.setChecked(true);
                break;
            case R.id.btn_save:
                SharedPreferences.Editor editor = getSharedPreferences("data",0).edit();
                editor.putString("Ip",editIP.getText().toString().trim());
                editor.putString("local",editlocal.getText().toString().trim());
                if(editface.getText().toString().trim().equals(0.0) || editface.getText().toString().trim().equals("")){
                    editor.putFloat("faceScore", Float.parseFloat(85.0+""));
                }else {
                    editor.putFloat("faceScore", Float.parseFloat(editface.getText().toString().trim()));
                }


                editor.commit();
                finish();
                break;
            case R.id.readInfo:

                rcPackage = new ResultPackage();
                giveValue();

                break;
            case R.id.btn_import_grou:

                // ExlUtils.getInstance().readExlData1(SetingSystemActivity.this,path1);
                // ExlUtils.getInstance().readExlData2(SetingSystemActivity.this,path2);
                //获取输入的身份证号码

                break;
            case R.id.btn_download:
                break;
            case R.id.btn_download_Test:
                break;

        }

    }

    public void giveValue(){


            rcPackage = new ResultPackage();
            rcPackage.m_strBeginTime = String.valueOf(System.currentTimeMillis()/1000);
            //考生数量
            rcPackage.m_nSporterNum = 0;
            rcPackage.m_strPackType = "PFPSporter";
            rcPackage.m_nEventType = String.valueOf(TCPConst.enumEvent.EventAllData.getIndex());
            textDate();
            new Thread(mRunnable).start();

 //        if(TextUtils.isEmpty(ip)){
//            Toast.makeText(this, "输入IP及端口号", Toast.LENGTH_SHORT).show();
//        }else {
//        }


    }

    public void textDate(){
        //rcPackage = new ResultPackage();
//        studentInfos = DataDao.queryAll();
//        for (int i = 0;i<studentInfos.size();i++) {
//            studentInfo = studentInfos.get(i);
//        }
        rcPackage.m_strClientName="";
        rcPackage.m_strServerName = "";
        rcPackage.m_nEventType = String.valueOf(TCPConst.enumEvent.EventScore.getIndex());
        rcPackage.m_strPackType = "SendCheckPackage";
        rcPackage.m_strGameEventName = "";
        // rcPackage. m_nSex = 0;
        //组别如：甲组
        rcPackage.m_strSort = "";
        //项目名称如：1000米
        rcPackage. m_strEvent = "";
        //赛次，-预赛，-次赛，-复赛，-决赛
        //rcPackage. m_nLayer =0;
        //分组，如：
        // rcPackage. m_nGrp = 0;
        //项目属性1-径赛，-田高，-田远，-接力，-全能
        //rcPackage.  m_nProperty = 0;
        //全能分项名称
        rcPackage. m_strAllEventName = "";
        //全能分项属性
        //rcPackage.  m_nAllProp  = 0;
        //全能分项序号
        // rcPackage.      m_nAllNum = 0;
        //风速，如：+1.2，-0.21
        rcPackage.m_strWindSpeed = "";
        //场次
        //rcPackage.  m_nField = 0;
        //检录状态
        // rcPackage. m_nCheck = 0;
        //成绩是否确认
        // rcPackage.  m_nAffirmFlag = 0;
        //考试地址
        rcPackage.m_strExamSitePlace = "";
        //分组ID
        //rcPackage.m_nGroupType = 0;

        for (int i = 0; i< rcPackage.m_nSporterNum; i++){
            //名次
            //rcPackage.m_nPlace[i] = 0;
            //道号
            //rcPackage.m_nTrackNO[i]= 0;
            //单位
            rcPackage.m_strUnitName[i] = "";
            rcPackage.m_strResult[i] = "";
            rcPackage.m_strNote[i] ="";


            rcPackage.m_strJudgeTime[i] = "";

            //单位代码
            rcPackage.m_strUnitCode[i] ="";
            //班级
            rcPackage.m_strClassName[i] = "";
            //考生类别
            rcPackage.m_strStudentCategory[i]= "";
            //最好成绩
            rcPackage.m_strBestScore[i] = "";
            //考试状态
            // rcPackage.m_nExamStatus[i] = 0;
        }
        for(int i =0; i<MAX_RECORD_COUNT;i++){
            rcPackage.m_strRecordRank[i] = "";
            rcPackage.m_strRecordResult[i] ="";
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
     //   mHandler.removeCallbacks(mRunnable);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == 0) {
            final String filePath = data.getStringExtra("filePath");
            if (null != filePath && filePath.length() > 0) {
                Toast.makeText(this, ""+filePath, Toast.LENGTH_SHORT).show();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mProgressDialog.setTitle(getString(R.string.loading));
                                mProgressDialog.setMessage(getString(R.string.preparing_device));
                                mProgressDialog.show();
                                ExlUtils.getInstance().readExlData3(SetingSystemActivity.this, filePath, new CallBack() {
                                    @Override
                                    public void onSucess(Object o) {

                                    }

                                    @Override
                                    public void onFail(String string) {

                                    }
                                });
                            }
                        });

            } else {
                Toast.makeText(SetingSystemActivity.this, "未选择文件",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }



    Runnable mRunnable =  new Runnable() {
        @Override
        public void run() {
            SharedPreferences sp=getSharedPreferences("data",0);
            ip = sp.getString("Ip", "");
            local = sp.getString("local", "");
            String datas = rcPackage.EncodePackage(new PackageHeadInfo(),false, TCPConst.enumCodeType.CodeGB2312.getIndex());
            new SocketClient().getTCPConnect(ip,Integer.parseInt(local),datas, new SocketClient.CallBackSocketTCP() {
                @Override
                public void Receive(String info) {

                }

                @Override
                public void isConnect(boolean state) {
                    Log.e( "连接状态-------->: ",state+"" );
                    if(state){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                stateText.setText(R.string.tcp_connect);
                            }
                        });


                    }else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                stateText.setText(R.string.tcp_Reconnect);
                            }
                        });


                    }
                }
            });

        }
    };


}
